package com.campusbackend.service.impl;

import com.campusbackend.entity.Students;
import com.campusbackend.entity.vo.StudentBasicInfoUpdateVO;
import com.campusbackend.entity.vo.StudentRegisterVO;
import com.campusbackend.entity.vo.StudentInfoVO;
import com.campusbackend.mapper.StudentsMapper;
import com.campusbackend.service.StudentsService;
import com.campusbackend.service.StudentSkillsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 学生用户表 服务实现类
 * </p>
 *
 * @author yezi
 * @since 2025-07-24
 */
@Service
public class StudentsServiceImpl extends ServiceImpl<StudentsMapper, Students> implements StudentsService {

    @Autowired
    private StudentsMapper studentsMapper;

    @Autowired
    private StudentSkillsService studentSkillsService;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public Students findByStudentId(String studentId) {
        return studentsMapper.findByStudentId(studentId);
    }

    @Override
    public List<Students> recommendStudents(String college) {
        return studentsMapper.recommendStudents(college);
    }

    @Override
    public List<Students> searchStudents(String college, String keyword) {
        return studentsMapper.searchStudents(college, keyword);
    }

    @Override
    @Transactional
    public String registerStudent(StudentRegisterVO registerVO) {
        // 1. 检查密码确认
        if (!registerVO.getPassword().equals(registerVO.getConfirmPassword())) {
            return "两次输入的密码不一致";
        }

        // 2. 检查学号是否已存在
        if (isStudentIdExists(registerVO.getStudentId())) {
            return "该学号已存在，请使用其他学号";
        }

        // 3. 检查邮箱是否已存在
        if (isEmailExists(registerVO.getEmail())) {
            return "该邮箱已被注册，请使用其他邮箱";
        }

        try {
            // 4. 创建学生实体
            Students student = new Students();
            student.setStudentId(registerVO.getStudentId());
            // 设置username为学号，因为登录时使用学号
            student.setUsername(registerVO.getStudentId());
            // 加密密码
            student.setPassword(passwordEncoder.encode(registerVO.getPassword()));
            student.setRealName(registerVO.getRealName());
            student.setAge(registerVO.getAge());
            student.setEmail(registerVO.getEmail());
            student.setCollege(registerVO.getCollege());

            // 设置默认值
            student.setAuditStatus((byte) 0); // 0-待审核
            student.setStatus((byte) 1); // 1-正常状态
            student.setCreateTime(LocalDateTime.now());
            student.setUpdateTime(LocalDateTime.now());

            // 5. 保存学生信息
            boolean saveResult = this.save(student);
            if (!saveResult) {
                return "注册失败，请稍后重试";
            }

            // 6. 保存学生技能关联
            boolean skillResult = studentSkillsService.saveStudentSkills(student.getId(), registerVO.getSkillIds());
            if (!skillResult) {
                return "技能信息保存失败，请稍后重试";
            }

            return "注册成功，请等待管理员审核";

        } catch (Exception e) {
            throw new RuntimeException("注册过程中发生错误", e);
        }
    }

    @Override
    public boolean isStudentIdExists(String studentId) {
        return studentsMapper.countByStudentId(studentId) > 0;
    }

    @Override
    public boolean isEmailExists(String email) {
        return studentsMapper.countByEmail(email) > 0;
    }

    @Override
    public boolean isEmailExistsExcludeCurrentUser(String email, String studentId) {
        return studentsMapper.countByEmailExcludeCurrentUser(email, studentId) > 0;
    }

    @Override
    public StudentInfoVO getStudentInfo(Long studentId) {
        // 1. 获取学生基本信息
        Students student = studentsMapper.selectById(studentId);
        if (student == null) {
            throw new RuntimeException("学生不存在");
        }

        // 2. 构建返回结果
        StudentInfoVO studentInfoVO = new StudentInfoVO();
        
        // 复制学生基本信息
        studentInfoVO.setStudentId(student.getId());
        studentInfoVO.setStudentNumber(student.getStudentId());
        studentInfoVO.setStudentName(student.getRealName());
        studentInfoVO.setCollege(student.getCollege());
        studentInfoVO.setAge(student.getAge());
        studentInfoVO.setEmail(student.getEmail());
        studentInfoVO.setPhone(student.getPhone());
        studentInfoVO.setAvatar(student.getAvatar());

        // 3. 获取队伍信息
        List<StudentInfoVO.TeamSimpleInfo> teams = studentsMapper.getStudentTeams(studentId);
        studentInfoVO.setTeams(teams);
        studentInfoVO.setTeamCount(teams != null ? teams.size() : 0);

        // 4. 获取技能信息
        List<StudentInfoVO.SkillSimpleInfo> skills = studentsMapper.getStudentSkills(studentId);
        studentInfoVO.setSkills(skills);
        studentInfoVO.setSkillCount(skills != null ? skills.size() : 0);

        return studentInfoVO;
    }

    @Override
    public String updateBasicInfo(String studentId, StudentBasicInfoUpdateVO updateVO) {
        try {
            // 1. 检查当前学生是否存在
            Students currentStudent = findByStudentId(studentId);
            if (currentStudent == null) {
                return "学生不存在";
            }

            // 2. 检查手机号是否被其他学生占用
            if (updateVO.getPhone() != null && !updateVO.getPhone().equals(currentStudent.getPhone()) 
                && isPhoneExistsExcludeCurrentUser(updateVO.getPhone(), studentId)) {
                return "该手机号已被其他学生注册，请使用其他手机号";
            }

            // 3. 检查邮箱是否被其他学生占用
            if (updateVO.getEmail() != null && !updateVO.getEmail().equals(currentStudent.getEmail()) 
                && isEmailExistsExcludeCurrentUser(updateVO.getEmail(), studentId)) {
                return "该邮箱已被其他学生注册，请使用其他邮箱";
            }

            // 4. 检查身份证号是否被其他学生占用
            if (updateVO.getIdCard() != null && !updateVO.getIdCard().equals(currentStudent.getIdCard()) 
                && isIdCardExistsExcludeCurrentUser(updateVO.getIdCard(), studentId)) {
                return "该身份证号已被其他学生注册，请检查身份证号是否正确";
            }

            // 5. 更新基本信息（只更新非空字段）
            if (updateVO.getPhone() != null) {
                currentStudent.setPhone(updateVO.getPhone());
            }
            if (updateVO.getEmail() != null) {
                currentStudent.setEmail(updateVO.getEmail());
            }
            if (updateVO.getCollege() != null) {
                currentStudent.setCollege(updateVO.getCollege());
            }
            if (updateVO.getAge() != null) {
                currentStudent.setAge(updateVO.getAge());
            }
            if (updateVO.getIdCard() != null) {
                currentStudent.setIdCard(updateVO.getIdCard());
            }
            currentStudent.setUpdateTime(LocalDateTime.now());

            // 6. 保存更新
            boolean updated = updateById(currentStudent);
            if (updated) {
                return "基本信息更新成功";
            } else {
                return "基本信息更新失败，请稍后重试";
            }

        } catch (Exception e) {
            return "更新基本信息时发生错误：" + e.getMessage();
        }
    }

    @Override
    public boolean isPhoneExistsExcludeCurrentUser(String phone, String studentId) {
        return studentsMapper.countByPhoneExcludeCurrentUser(phone, studentId) > 0;
    }

    @Override
    public boolean isIdCardExistsExcludeCurrentUser(String idCard, String studentId) {
        return studentsMapper.countByIdCardExcludeCurrentUser(idCard, studentId) > 0;
    }
}
